﻿using Dapper;
using EWC.Core.Application.Dtos;
using EWC.Core.DependencyInjection;
using EWC.HIS.Dapper.Data;
using EWC.HIS.Domain;
using EWC.HIS.Domain.Data.Repositories;
using EWC.HIS.Domain.Entities;
using EWC.HIS.Domain.ViewManage.Do;
using EWC.HIS.Domain.ViewManage.Repositories;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace EWC.HIS.Dapper.ViewManage.Repositories
{
    public class ViewRepository : RepositoryBase<BaseEntity>, IViewRepository, IScopedDependency
    {
        public ViewRepository(IDbContext dbContext) : base(dbContext)
        {
        }

        public virtual async Task<PagedResultDto<DepartmentDo>> GetPagedDepartments(string departmentName, string departmentCategory, int pageIndex, int pageSize)
        {
            using (IDbConnection session = await DbContext.GetConnectionAsync())
            {
                string searchQuery = "SELECT [科室代码] AS DeptCode, [科室名称] AS DeptName, [科室类别] AS DeptCategory, [HIS中的原始科室代码] AS HISOriginalDeptCode, [所属院区代码] AS BelongsHospitalDistrictCode, [专业类别] AS ProfessionalCategory, [联系电话] AS ContactNumber, [上级科室代码] AS SuperiorDeptCode, [床位数] AS BedNumber FROM [EHIS].[dbo].[VW_Lis_Dict_Dept]";
                string countQuery = "SELECT COUNT(1) FROM [EHIS].[dbo].[VW_Lis_Dict_Dept]";

                var parameters = new DynamicParameters();
                parameters.Add("DepartmentName", $"%{departmentName}%");
                parameters.Add("DepartmentCategory", $"%{departmentCategory}%");
                parameters.Add("PageIndex", pageIndex);
                parameters.Add("PageSize", pageSize);

                if (!string.IsNullOrEmpty(departmentName))
                {
                    searchQuery += " WHERE [科室名称] LIKE @DepartmentName";
                    countQuery += " WHERE [科室名称] LIKE @DepartmentName";
                }

                if (!string.IsNullOrEmpty(departmentCategory))
                {
                    searchQuery += " AND [科室类别] LIKE @DepartmentCategory";
                    countQuery += " AND [科室类别] LIKE @DepartmentCategory";
                }

                searchQuery += " ORDER BY [科室代码] OFFSET @PageIndex * @PageSize ROWS FETCH NEXT @PageSize ROWS ONLY;";

                var departments = await session.QueryAsync<DepartmentDo>(searchQuery, parameters);
                var totalRecords = await session.QuerySingleOrDefaultAsync<int>(countQuery, parameters);

                return new PagedResultDto<DepartmentDo>
                {
                    Items = departments.ToList(),
                    PageIndex = pageIndex,
                    PageSize = pageSize,
                    TotalCount = totalRecords
                };
            }
        }
    }
}
